'use strict';

const Controller = require('egg').Controller;
class CommonController extends Controller {
  async login() {
    const { ctx, app } = this;
    const loginRule = {
      phone: { type: 'string', trim: true },
      password: { type: 'string', trim: true },
    };
    const data = ctx.request.body;
    ctx.validate(loginRule, data);
    const user = await ctx.service.user.findUserByPhoneAndPassword(data);
    if (user) {
      const token = ctx.helper.getToken(app, {
        id: user[0].id,
        phone: data.phone,
      });
      user[0].access_token = token;
    }
    return ctx.helper.success({
      ctx,
      data: user[0],
      msg: user ? '登陆成功' : '用户不存在或密码错误',
    });
  }

  async register() {
    const { ctx } = this;
    try {
      const registerRule = {
        username: { type: 'string', trim: true },
        phone: { type: 'string', trim: true },
        password: { type: 'string', trim: true },
      };
      const data = ctx.request.body;
      ctx.validate(registerRule, data);
      const { _id } = await ctx.service.user.addUser(data);
      return ctx.helper.success({ ctx, data: { id: _id } });
    } catch (err) {
      return ctx.helper.fail({ ctx, msg: '该用户名或手机号已被注册' });
    }
  }
}

module.exports = CommonController;
